import React, { useEffect, useState, useRef } from "react";
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  message,
  Select,
  Pagination,
  Upload,
  Card,
  Typography,
  Image,
  Popover,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import type { TableRowSelection } from "antd/es/table/interface";
import { UploadOutlined, DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { studentApi, avatarApi } from "../../services/api";

interface Student {
  id: number;
  username: string;
  name: string;
  phone: string;
  email: string;
  role: string;
  sex: number;
  grade: string;
  hobby: string;
  introduction: string;
  avatar?: string;
}

const { Title } = Typography;

const StudentPage: React.FC = () => {
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);
  const [pageTotal, setPageTotal] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<Student[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
  const fileInputRef = useRef<any>(null);

  const columns: ColumnsType<Student> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
      width: 80,
    },
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "电话",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "邮箱",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "年级",
      dataIndex: "grade",
      key: "grade",
    },
    {
      title: "性别",
      dataIndex: "sex",
      key: "sex",
      render: (sex: number) => (sex === 1 ? "男" : "女"),
    },
    {
      title: "头像",
      dataIndex: "avatar",
      key: "avatar",
      render: (avatar: string) => (
        avatar ? (
          <Image
            src={avatar}
            alt="头像"
            style={{ width: 50, height: 50, borderRadius: '50%', cursor: 'pointer' }}
            preview={{
              visible: false,
            }}
            onClick={(e) => {
              e.stopPropagation();
              setPreviewImage(avatar);
              setPreviewOpen(true);
            }}
          />
        ) : (
          <div style={{ width: 50, height: 50, borderRadius: '50%', background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            无头像
          </div>
        )
      ),
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => handleEdit(record)}>编辑</a>
          <Popconfirm
            title="确定删除此学生吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ color: "#ff4d4f" }}>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const rowSelection: TableRowSelection<Student> = {
    selectedRowKeys,
    onChange: (selectedRowKeys: React.Key[], selectedRows: Student[]) => {
      setSelectedRowKeys(selectedRowKeys);
      setSelectedRows(selectedRows);
    },
  };

  const fetchStudents = async () => {
    setLoading(true);
    try {
      const response = await studentApi.selectAll();
      setStudents(response.data || []);
    } catch (error) {
      message.error("获取学生列表失败");
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (record: Student) => {
    setEditingId(record.id);
    form.setFieldsValue(record);
    setAvatarUrl(record.avatar || null);
    setOpen(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await studentApi.delete(id);
      message.success("删除成功");
      fetchStudentsByPage(1, 10);
    } catch (error) {
      message.error("删除失败");
    }
  };

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setAvatarUrl(null);
    setOpen(true);
  };

  // 头像上传处理
  const handleAvatarUpload = async (file: any) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await avatarApi.upload(formData);
      setAvatarUrl(response.data);
      message.success('头像上传成功');
    } catch (error) {
      message.error('头像上传失败');
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const studentData = { ...values, avatar: avatarUrl };
      
      if (editingId) {
        await studentApi.update({ ...studentData, id: editingId });
        message.success("更新成功");
      } else {
        await studentApi.add(studentData);
        message.success("添加成功");
      }
      setOpen(false);
      fetchStudentsByPage(1, 10);
    } catch (error) {
      message.error("操作失败");
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const fetchStudentsByPage = async (current: number, pageSize: number) => {
    setLoading(true);
    try {
      const response = await studentApi.selectPage({
        pageNum: current,
        pageSize,
      });
      setStudents(response.data.list || []);
      setPageTotal(response.data.total);
      // 重置选中项
      setSelectedRowKeys([]);
      setSelectedRows([]);
    } catch (error) {
      message.error("获取学生列表失败");
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async () => {
    try {
      setLoading(true);
      // 如果有选中的行，则只导出选中的数据
      const params =
        selectedRowKeys.length > 0 ? { ids: selectedRowKeys.join(",") } : {};

      const response = await studentApi.exportData(params);
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "students.xlsx");
      document.body.appendChild(link);
      link.click();
      link.remove();
      message.success("导出成功");
    } catch (error) {
      message.error("导出失败");
    } finally {
      setLoading(false);
    }
  };

  // 导入数据
  const handleImport = async (file: any) => {
    try {
      const formData = new FormData();
      formData.append("file", file);
      setLoading(true);
      await studentApi.importData(formData);
      message.success("导入成功");
      fetchStudentsByPage(1, 10);
    } catch (error) {
      message.error("导入失败");
    } finally {
      setLoading(false);
    }
    return false;
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRows.length === 0) {
      message.warning("请先选择要删除的学生");
      return;
    }

    try {
      // 后端接口需要接收完整的Student对象列表，而不是ID列表
      await studentApi.deleteBatch(selectedRows.map(row => row.id).join(','));
      message.success("批量删除成功");
      fetchStudentsByPage(1, 10);
    } catch (error) {
      message.error("批量删除失败");
    }
  };

  useEffect(() => {
    fetchStudentsByPage(1, 10);
  }, []);

  function onShowSizeChange(current: number, size: number): void {
    // 分页查询逻实现
    fetchStudentsByPage(current, size);
  }

  // 头像上传前的处理
  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    
    handleAvatarUpload(file);
    return false;
  };

  return (
    <div>
      <Card
        title={
          <Title level={4} style={{ margin: 0, color: "#0052D9" }}>
            学生管理
          </Title>
        }
        extra={
          <div>
            <Button
              type="primary"
              onClick={handleAdd}
              style={{ marginRight: 8 }}
            >
              添加学生
            </Button>
            <Button
              type="default"
              onClick={handleExport}
              style={{ marginRight: 8 }}
              disabled={loading}
            >
              {selectedRowKeys.length > 0
                ? `导出选中(${selectedRowKeys.length})`
                : "导出数据"}
            </Button>
            <Upload
              beforeUpload={handleImport}
              showUploadList={false}
              accept=".xlsx,.xls"
            >
              <Button icon={<UploadOutlined />} disabled={loading} style={{ marginRight: 8 }}>
                导入数据
              </Button>
            </Upload>
            <Popover 
              content={`已选择 ${selectedRowKeys.length} 项`}
              title="批量操作"
              trigger="hover"
            >
              <Button 
                icon={<DeleteOutlined />} 
                onClick={handleBatchDelete}
                disabled={selectedRowKeys.length === 0}
                danger
              >
                批量删除
              </Button>
            </Popover>
          </div>
        }
        style={{ padding: 0 }}
      >
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={students}
          loading={loading}
          rowKey="id"
          pagination={false}
          scroll={{ x: "max-content" }}
        />

        <div
          style={{
            padding: "16px",
            display: "flex",
            justifyContent: "flex-end",
          }}
        >
          <Pagination
            showSizeChanger
            onShowSizeChange={onShowSizeChange}
            defaultCurrent={1}
            total={pageTotal}
            onChange={fetchStudentsByPage}
            showTotal={(total) => `共 ${total} 条记录`}
          />
        </div>
      </Card>

      {/* Table and Pagination components have been moved into the Card component above */}
      <Modal
        title={
          <span style={{ color: "#0052D9" }}>
            {editingId ? "编辑学生" : "添加学生"}
          </span>
        }
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="请输入姓名" />
          </Form.Item>

          <Form.Item name="phone" label="电话">
            <Input placeholder="请输入电话" />
          </Form.Item>

          <Form.Item name="email" label="邮箱">
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item name="grade" label="年级">
            <Input placeholder="请输入年级" />
          </Form.Item>

          <Form.Item name="sex" label="性别">
            <Select placeholder="请选择性别">
              <Select.Option value={1}>男</Select.Option>
              <Select.Option value={0}>女</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="hobby" label="爱好">
            <Input placeholder="请输入爱好" />
          </Form.Item>

          <Form.Item name="introduction" label="简介">
            <Input.TextArea placeholder="请输入简介" rows={3} />
          </Form.Item>

          <Form.Item label="头像">
            <Upload
              name="avatar"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={beforeUpload}
            >
              {avatarUrl ? (
                <img src={avatarUrl} alt="avatar" style={{ width: '100%' }} />
              ) : (
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>上传</div>
                </div>
              )}
            </Upload>
            {avatarUrl && (
              <Button 
                onClick={() => setAvatarUrl(null)} 
                style={{ marginTop: 8 }}
                danger
              >
                删除头像
              </Button>
            )}
          </Form.Item>
        </Form>
      </Modal>

      {/* 图片预览 */}
      {previewImage && (
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
          }}
          src={previewImage}
        />
      )}
    </div>
  );
};

export default StudentPage;